package com.ruoyi.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.FileEntity;
import com.ruoyi.mapper.FileEntityMapper;
import com.ruoyi.service.FileEntityService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;

@Service
public class FileEntityServiceImpl implements FileEntityService {
    @Autowired
    private FileEntityMapper fileEntityMapper;
    @Override
    public R addFileEntity(List<FileEntity> fileEntityList) {
        try {
       if (fileEntityList.size()==0){
           return R.ok();
       }
        List<FileEntity> fileEntities = fileEntityMapper.getFileListByRowId(fileEntityList.get(0).getRowId());
            if (CollectionUtils.isNotEmpty(fileEntities)){
             for (FileEntity fle:fileEntityList){
                 FileEntity fileEntity = fileEntityMapper.getFileListByRowIdAndFileType(fle.getRowId(),fle.getFileType());
                 if (fileEntity!=null){
                     fileEntityMapper.updateByidAndtype(fle);
                 }else{
                     Long userid = getUserId();
                     String time = DateUtils.getTime();
                     fle.setUid(userid);
                     fle.setCreatedBy(userid);
                     LocalDateTime localDateTimeNow =   LocalDateTime.now();
                     fle.setUploadTime(localDateTimeNow);
                     fileEntityMapper.addFileEntity(fle);
                 }
              }
            }

            else{
                for (FileEntity file:fileEntityList) {
                    Long userid = getUserId();
                    String time = DateUtils.getTime();
                    file.setUid(userid);
                    file.setCreatedBy(userid);
                    LocalDateTime localDateTimeNow =   LocalDateTime.now();
                    file.setUploadTime(localDateTimeNow);
                    fileEntityMapper.addFileEntity(file);
                }
            }
            return R.ok();
        }catch (Exception e){
            System.out.println("addFileEntity:"+e);
            return R.fail("增加文件存储失败");
        }
    }

    @Override
    public R getFileList(String taskId ,Long userId) {
        return R.ok( fileEntityMapper.getFileList(taskId,userId));
    }

    @Override
    public R getFileListByRowId(String rowId) {
        return R.ok(fileEntityMapper.getFileListByRowId(rowId));
    }









}
